<template>
  <!-- 订货计划表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="850px"
    top="5vh"
    draggable
    @close="closeDialog"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <div class="search-container">
      <el-form
        ref="formRef"
        :model="formData"
        label-width="120px"
        style="display: flex"
      >
        <el-row>
          <!-- 工厂号-->
          <el-col :span="12">
            <el-form-item label="工厂">
              <el-select
                @change="plantChange"
                v-model="formData.plantId"
                placeholder="请选择"
                style="width: 250px"
                disabled
              >
                <el-option
                  v-for="item in plants"
                  :key="item.id"
                  :label="item.organizationCode"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商">
              <el-select
                @change="partnerChange"
                v-model="formData.partnerId"
                placeholder="请选择"
                style="width: 250px"
                disabled
              >
                <el-option
                  v-for="item in partners"
                  :key="item.id"
                  :label="item.partnerName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--物料号-->
          <el-col :span="12">
            <el-form-item label="物料">
              <el-select
                @change="materialChange"
                v-model="formData.materialId"
                placeholder="请选择"
                style="width: 250px"
                disabled
              >
                <el-option
                  v-for="item in materials"
                  :key="item.materialId"
                  :label="item.materialName"
                  :value="item.materialId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--计划到货日期-->
          <el-col :span="12">
            <el-form-item label="计划到货日期">
              <el-date-picker
                v-model="formData.arriveDate"
                type="date"
                placeholder="请输入到货日期"
                style="width: 250px"
                :disabled-date="disabledDate"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卸货口">
              <el-select
                @change="dischargehatchChange"
                v-model="formData.dischargeHatchId"
                placeholder="请选择"
                style="width: 250px"
                disabled
              >
                <el-option
                  v-for="item in dischargehatchs"
                  :key="item.id"
                  :label="item.dischargeHatchCode"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--      计划采购数量-->
          <el-col :span="12">
            <el-form-item label="要货数量">
              <el-input-number
                v-model="formData.planQuantity"
                :min="1"
                style="width: 250px"
                disabled
              />
            </el-form-item>
          </el-col>
          <!--备注-->
          <el-form-item label="备注">
            <el-input
              v-model="formData.remarks"
              placeholder="请输入备注"
              type="textarea"
              :rows="2"
              style="width: 645px"
              disabled
            />
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
      >
        <el-table-column type="index" label="序号" align="center" width="100" />
        <el-table-column
          label="当前数量"
          prop="currentQuantity"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="变更前数量"
          prop="beforeQuantity"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="修改时间"
          prop="lastUpdateTime"
          min-width="100"
          show-overflow-tooltip
        />
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">关 闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "SRMSRMPLANSCHEDULELOG",
  inheritAttrs: false,
});

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const emit = defineEmits(["reset-table", "change-visible", "select-row"]);

// 工厂
let plants: any = ref([]);
// 物料号
let materials: any = ref([]);
// 供应商
let partners: any = ref([]);
// 卸货口
let dischargehatchs: any = ref([]);

const formRef = ref(ElForm);

// 请求参数
const requestApi = "/mes/srmplanschedulelog/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  planId: "",
};

const deleteParam = {
  api: "/mes/srmplanschedulelog/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

let formData = reactive({
  id: "",
  planId: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  partnerId: "",
  partnerCode: "",
  partnerName: "",
  dischargeHatchId: "",
  dischargeHatchCode: "",
  dischargeHatchName: "",
  arriveDate: "",
  arriveYear: "",
  arriveMonth: "",
  arriveWeek: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  planQuantity: 0,
  replyUserId: "",
  replyUserName: "",
  agreeQuantity: "",
  replyTime: "",
  replyContent: "",
  orderScheduleState: "",
  isPacking: "",
  packagingStep: "",
  isExecute: "",
  allowSend: "",
  enabled: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
});

onMounted(() => {
  getPlants();
  getPartners();
  if (formData.plantId) {
    getDischargehatchs();
  }
  if (formData.partnerId) {
    getMaterials();
  }
  if (formData.id) {
    searchParam.value.planId = formData.id;
    getTableList();
  }
});

// 供应商查询
async function getPartners() {
  const data = await request({
    url: "/mes/core/mdmpartner/getList",
    method: "post",
    data: {},
  });
  partners.value = data.data;
}

// 工厂查询
async function getPlants() {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plants.value = data;
}

function plantChange() {
  dischargehatchs.value = [];
  formData.dischargeHatchId = "";
  formData.dischargeHatchCode = "";
  formData.dischargeHatchName = "";
  const plan = plants.value.find((item) => {
    return item.id === formData.plantId;
  });
  formData.plantCode = plan.organizationCode;
  formData.plantName = plan.organizationName;
  getDischargehatchs();
}

function partnerChange() {
  materials.value = [];
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  const partner = partners.value.find((item) => {
    return item.id === formData.partnerId;
  });
  formData.partnerCode = partner.partnerCode;
  formData.partnerName = partner.partnerName;
  getMaterials();
}

async function getMaterials() {
  const data = await request({
    url: `/mes/core/partnerproduct/materialList/` + formData.partnerId,
    method: "get",
  });
  materials.value = data.data;
}

function materialChange() {
  const material = materials.value.find((item) => {
    return item.materialId === formData.materialId;
  });
  formData.materialCode = material.materialCode;
  formData.materialName = material.materialName;
}

async function getDischargehatchs() {
  const data = await request({
    url: `/mes/srmdischargehatch/getDropdownList/` + formData.plantId,
    method: "get",
  });
  dischargehatchs.value = data.data;
}

function dischargehatchChange() {
  const dischargehatch = dischargehatchs.value.find((item) => {
    return item.id === formData.dischargeHatchId;
  });
  formData.dischargeHatchCode = dischargehatch.dischargeHatchCode;
  formData.dischargeHatchName = dischargehatch.dischargeHatchName;
}

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (newVal) {
      // getTableList();
    }
  }
);

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        planId,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        partnerId,
        partnerCode,
        partnerName,
        dischargeHatchId,
        dischargeHatchCode,
        dischargeHatchName,
        arriveDate,
        arriveYear,
        arriveMonth,
        arriveWeek,
        materialId,
        materialCode,
        materialName,
        planQuantity,
        replyUserId,
        replyUserName,
        agreeQuantity,
        replyTime,
        replyContent,
        orderScheduleState,
        isPacking,
        packagingStep,
        isExecute,
        allowSend,
        enabled,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        planId,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        partnerId,
        partnerCode,
        partnerName,
        dischargeHatchId,
        dischargeHatchCode,
        dischargeHatchName,
        arriveDate,
        arriveYear,
        arriveMonth,
        arriveWeek,
        materialId,
        materialCode,
        materialName,
        planQuantity,
        replyUserId,
        replyUserName,
        agreeQuantity,
        replyTime,
        replyContent,
        orderScheduleState,
        isPacking,
        packagingStep,
        isExecute,
        allowSend,
        enabled,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      });
      getPlants();
      getPartners();
      getMaterials();
      getDischargehatchs();
    }
    if (formData.id) {
      searchParam.value.planId = formData.id;
      getTableList();
    }
  }
);

/** 重置表单 */
/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.planId = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.partnerId = "";
  formData.partnerCode = "";
  formData.partnerName = "";
  formData.dischargeHatchId = "";
  formData.dischargeHatchCode = "";
  formData.dischargeHatchName = "";
  formData.arriveDate = "";
  formData.arriveYear = "";
  formData.arriveMonth = "";
  formData.arriveWeek = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.planQuantity = 1;
  formData.replyUserId = "";
  formData.replyUserName = "";
  formData.agreeQuantity = "";
  formData.replyTime = "";
  formData.replyContent = "";
  formData.orderScheduleState = "";
  formData.isPacking = "";
  formData.packagingStep = "";
  formData.isExecute = "";
  formData.allowSend = "";
  formData.enabled = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
}

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}
</script>
